#include "resource.h"
#include "config.h"
#include <iostream>

using std::cerr;
using std::endl;

static uint64_t tick;
static MutexType tickMutex;

double Resource::getMoney()const{ return money; }

double Resource::getEnergy()const{ return energy; }

Resource::Resource(){
    money = 0;
    energy = 0;
    startTime = time(NULL);
}

Resource::Resource(double money, double energy): money(money), energy(energy){
    startTime = time(NULL);
}

bool Resource::consumeMoney(double consume){
    if (money - consume < 0){
#if USE_LOG
        cerr << "**************************************************" << endl;
        cerr << "金钱不足" << endl;
        cerr << "金钱数量: " << money << endl;
        cerr << "目标地址: " << (void *)this << endl;
        cerr << "**************************************************" << endl;
#endif
        return false;
    }
    money -= consume;
    return true;
}

bool Resource::consumeEnergy(double consume){
    if (energy - consume < 0){
#if USE_LOG
        cerr << "**************************************************" << endl;
        cerr << "能源不足" << endl;
        cerr << "能源数量: " << energy << endl;
        cerr << "目标地址: " << (void *)this << endl;
        cerr << "**************************************************" << endl;
#endif
        return false;
    }
    energy -= consume;
    return true;
}

GameTimeType NowTime(){
    GameTimeType tmp = 0;
    if (MUTEX_TRY_LOCK(mutex)){
        tmp = tick;
        MUTEX_UNLOCK(mutex);
    }
    return tmp;
}

void TickAdd(){
    if (MUTEX_TRY_LOCK(mutex)){
        tick += 1;
        MUTEX_UNLOCK(mutex);
    }
}

void TickInit(){
    tick = 1;
    MUTEX_INIT(mutex);
}

